package com.mallotec.android.timenote.util;

import android.app.Activity;
import android.content.Context;
import android.widget.EditText;

import androidx.fragment.app.FragmentActivity;

import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author reborn
 * @program TimeNote
 * @description
 * @create 2020-11-14 13:07
 **/
public class DateTimeUtil {

    public static Calendar stringToCalendar(String datetime) throws ParseException {
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date =sdf.parse(datetime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    public static String calendarToString(Calendar calendar) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return sdf.format(calendar.getTime());
    }

    public static void pickDateTime(FragmentActivity activity, EditText editText) {
        Calendar now = Calendar.getInstance();
        StringBuilder datetime = new StringBuilder();
        DatePickerDialog dpd = DatePickerDialog.newInstance(
                (view1, year, monthOfYear, dayOfMonth) -> {
                    String date = year + "/" + (monthOfYear + 1) + "/" + dayOfMonth;
                    datetime.append(date);
                    TimePickerDialog tpd = TimePickerDialog.newInstance(
                            (view2, hourOfDay, minute, second) -> {
                                String time = String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute) + ":" + String.format("%02d", second);
                                datetime.append(" ").append(time);
                                editText.setText(datetime.toString());
                            },
                            now.get(Calendar.HOUR_OF_DAY),
                            now.get(Calendar.MINUTE),
                            now.get(Calendar.SECOND),
                            true
                    );
                    tpd.show(activity.getSupportFragmentManager(), "StartTimePickerDialog");
                },
                now.get(Calendar.YEAR), // Initial year selection
                now.get(Calendar.MONTH), // Initial month selection
                now.get(Calendar.DAY_OF_MONTH) // Inital day selection
        );
        dpd.show(activity.getSupportFragmentManager(), "StartDatePickerDialog");
    }
}
